<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:replace="inc/header"></head>

<body th:with="menu='content'" >
<nav th:replace="inc/nav"></nav>

<div class="container-fluid">
  <div class="row">
    <div th:replace="inc/sidebar"></div>
    <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
      <h1 class="page-header">
        <span id="pageHeader"></span>
        <div class="pull-right">
          <button class="btn btn-primary btn-sm" id="btnSave">保存</button>
        </div>
      </h1>
      <form id="contentForm" class="form-horizontal">
        <input type="hidden" th:value="${jsbh}" name="jsbh" id="jsbh">
        <input type="hidden" name="id" id="id">
        <div class="form-group">
          <label for="subType" class="col-md-3 control-label">一级分类</label>
          <div class="col-md-9">
            <select class="form-control" name="subType" id="subType" required>
              <option value="">---请选择---</option>
            </select>
          </div>
        </div>
        <div class="form-group">
          <label for="typeId" class="col-md-3 control-label">二级分类</label>
          <div class="col-md-9">
            <select class="form-control" name="typeId" id="typeId" required>
              <option value="">---请选择---</option>
            </select>
          </div>
        </div>
        <div class="form-group">
          <label for="title" class="col-md-3 control-label">标题</label>
          <div class="col-md-9">
            <input type="text" class="form-control" name="title" id="title" required>
          </div>
        </div>
        <div class="form-group">
          <label for="miniTitle" class="col-md-3 control-label">标题缩写</label>
          <div class="col-md-9">
            <input type="text" class="form-control" name="miniTitle" id="miniTitle" required>
          </div>
        </div>
        <div class="form-group">
          <label for="content" class="col-md-3 control-label">内容</label>
          <div class="col-md-9">
            <textarea class="form-control" name="content" id="content"></textarea>
          </div>
        </div>
      </form>
    </div>
  </div>
</div>

<div th:replace="inc/footer"></div>
<script th:inline="javascript">
  $(function () {
    // 编辑器
    CKEDITOR.replace('content');

    // 模式：新增/编辑
    var mode = [[${mode}]];

    // 编辑模式缓存
    var content = {};

    if (mode === 'edit') {
      $('#pageHeader').text('修改信息发布');
    } else {
      $('#pageHeader').text('新增信息发布');
    }

    // 加载内容，作为获取分类后的回调
    var loadContent = function () {
      $.ajax({
        url: [[${#httpServletRequest.getContextPath()} + '/content/getById']],
        data: {
          id: UTILS.getUrlParamByName('id')
        },
        success: function (data) {
          content = data;
          $('#subType').val(content.type.subType).trigger('change');
          $('#jsbh').val(content.jsbh);
          $('#id').val(content.id);
          $('#title').val(content.title);
          $('#miniTitle').val(content.miniTitle);
          CKEDITOR.instances.content.setData(content.content);
        },
        error: function () {
          alert('加载内容出错')
        }
      })
    };

    // 获取分类
    var contentTypeMap = {};
    $.ajax({
      url: [[${#httpServletRequest.getContextPath()} + '/ct/findAll']],
      success: function (data) {
        data.forEach(function (type) {
          contentTypeMap[type.subType] = contentTypeMap[type.subType] || [];
          contentTypeMap[type.subType].push(type)
        });
        Object.keys(contentTypeMap).forEach(function (subType) {
          $('#subType').append($('<option>', {value: subType}).text(subType==='infoIssue'?'信息发布':'法律法规'))
        });

        // 编辑模式填入数据
        if (mode === 'edit') {
          loadContent()
        }
      }
    });

    // 二级分类选择事件
    $('#subType').on('change', function () {
      var subType = $(this).val();
      var $contentType = $('#typeId');
      $contentType.empty().append('<option value="">---请选择---</option>');
      if (subType in contentTypeMap) {
        contentTypeMap[subType].forEach(function (type) {
          $contentType.append($('<option>', {value: type.id}).text(type.name))
        })
      }

      // 编辑模式填入数据
      if (mode === 'edit') {
        $contentType.val(content.type.id)
      }
    });

    var $contentForm = $('#contentForm');
    // 表单验证
    $contentForm.validate();

    // 保存按钮
    $('#btnSave').on('click', function () {
      // 表单验证
      if (!$contentForm.valid()) return;

      var data = $contentForm.serializeDict();
      data.content = CKEDITOR.instances.content.getData();
      data.type = {
        id: parseInt(data.typeId)
      };

      // 提交
      $.ajax({
        url: [[${#httpServletRequest.getContextPath()} + '/content/save']],
        method: 'post',
        data: JSON.stringify(data),
        contentType: 'application/json',
        dataType:"text",
        success: function (result) {
          var jsbh = [[${jsbh}]];
          if (mode === 'edit') {
            jsbh = content.jsbh
          }
          location.href = [[${#httpServletRequest.getContextPath()} + '/content/admin/main?jsbh=']] + jsbh;
        },
        error: function () {
          alert('保存出错');
        }
      })
    })
  });
</script>
</body>
</html>
